﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ue.Framework.Web.WebControls;
using Ue.Infrastructure.Web.UI;
using Ue.Qcdz.Domain.Membership;

namespace Ue.Qcdz.UI.Controls
{
    public class UserChangePassword : SkinnedControl
    {
        private TextBox tbxOldPassword;
        private TextBox tbxNewPassword;
        private TextBox tbxNewPasswordAg;
        private Button btnSubmit;
        private string skinFileName = "~/Themes/zh-cn/Skins/UserChangePassword.ascx";
        protected override string GetSkinFileName()
        {
            return skinFileName;
        }

        protected override void InitializeSkin(Control skin)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                tbxOldPassword = skin.FindControl<TextBox>("tbxOldPassword");
                tbxNewPassword = skin.FindControl<TextBox>("tbxNewPassword");
                tbxNewPasswordAg = skin.FindControl<TextBox>("tbxNewPasswordAg");
                btnSubmit = skin.FindControl<Button>("btnSubmit");
                btnSubmit.Click += new EventHandler(btnSubmit_Click);
            }

        }

        void btnSubmit_Click(object sender, EventArgs e)
        {
            string strOldPassword = Ue.Framework.Security.DEncryptUtils.MD5EnCode(tbxOldPassword.GetValue<string>());
            string strNewPassword = Ue.Framework.Security.DEncryptUtils.MD5EnCode(tbxNewPassword.GetValue<string>());
            string strNewPasswordAg = Ue.Framework.Security.DEncryptUtils.MD5EnCode(tbxNewPasswordAg.GetValue<string>());
            if (strNewPassword.Equals(strNewPasswordAg))
            {
                ChangePassword(strOldPassword, strNewPassword);
            }
            this.MessageWindow.RenderMessage("两次输入的密码不一样");

        }
        private void ChangePassword(string strOldPassword, string strNewPassword)
        {
            string strUserName = HttpContext.Current.User.Identity.Name;
            IUserRepository repository =
                Ue.Infrastructure.RepositoryFramework.RepositoryFactory.GetRepository<IUserRepository, User>();
            User user = repository.FindBy(strUserName);
            if (user != null)
            {
                if (user.ChangePassword(strOldPassword, strNewPassword))
                {
                    repository[user.Key] = user;
                    this.MessageWindow.RenderMessage("修改成功");
                }
                else
                {
                    this.MessageWindow.RenderMessage("修改失败,原密码错误");
                }
            }
        }



    }
}
